<style>
  #febs-approvals xm-select {
    min-height: 30px;
    line-height: 30px;
  }
  #febs-approvals xm-select > .xm-label .scroll .label-content {
    display: flex;
    padding: 0 30px 0 10px;
  }
</style>
<div class="layui-fluid layui-anim febs-anim" id="febs-approvals" lay-title="单据签核作业">
  <div class="layui-row febs-container">
    <div class="layui-col-md12">
      <div class="layui-card">
        <div class="layui-card-body febs-table-full">
          <form class="layui-form layui-table-form" lay-filter="user-table-form">
            <div class="layui-row">
              <div class="layui-col-md10">
                <div class="layui-form-item">
                  <div class="layui-inline">
                    <label class="layui-form-label layui-form-label-sm">厂别</label>
                    <div class="layui-input-inline">
                      <select id="orgId" name="orgId">
                        <option value=""></option>
                      </select>
                    </div>
                  </div>
                  <div class="layui-inline">
                    <label class="layui-form-label layui-form-label-sm">单据分类</label>
                    <div class="layui-input-inline">
                      <select id="billstdNo" name="billstdNo">
                        <option value=""></option>
                      </select>
                    </div>
                  </div>
                  <div class="layui-inline">
                    <label class="layui-form-label layui-form-label-sm">单据</label>
                    <div class="layui-input-inline">
                      <input type="text" name="orderNo" autocomplete="off" class="layui-input" />
                    </div>
                  </div>
                  <div class="layui-inline">
                    <label class="layui-form-label layui-form-label-sm">送签人员</label>
                    <div class="layui-input-inline">
                      <input type="text" name="grtUserCname" autocomplete="off" class="layui-input" />
                    </div>
                  </div>
                  <div class="layui-inline">
                    <label class="layui-form-label layui-form-label-sm">送签日期</label>
                    <div class="layui-input-inline">
                      <input type="text" name="time" id="user-signTime" class="layui-input" />
                    </div>
                  </div>
                </div>
              </div>
              <div class="layui-col-md2 layui-col-sm12 layui-col-xs12 table-action-area">
                <div class="layui-btn layui-btn-sm layui-btn-primary febs-button-blue-plain table-action" id="query">
                  <i class="layui-icon">&#xe848;</i>
                </div>
                <div class="layui-btn layui-btn-sm layui-btn-primary febs-button-green-plain table-action" id="reset">
                  <i class="layui-icon">&#xe79b;</i>
                </div>
                <div
                        class="layui-btn layui-btn-sm layui-btn-primary table-action action-more"
                        shiro:hasAnyPermissions="reject:add">
                  <i class="layui-icon">&#xe875;</i>
                </div>
              </div>
            </div>
          </form>
          <div id="batchSign" shiro:hasPermission="approvals:sign" class="layui-btn layui-btn-sm layui-btn-primary febs-button-blue-plain table-action">批量签核</div>
          <table lay-filter="approvalTable" lay-data="{id: 'approvalTable'}"></table>
        </div>
      </div>
    </div>
  </div>
</div>
<script type="text/html" id="approvals-status">
  {{# let chkStatus = { 2: {title: '已签', color: 'green'}, 1: {title: '待签', color: 'volcano'} }[d.chkStatus]; }}
  <span class="layui-badge febs-bg-{{chkStatus.color || 'volcano'}}">{{ chkStatus.title || '??'}}</span>
</script>
<!-- <script type="text/html" id="approvals-orgId">
  {{# let orgId = { 1201: {title: '站成AD厂'}, 9001: {title: 'AD开发中心'}, 9002: {title: 'NB开发中心'}, 1350: {title: '安乡站成底厂'}, 9003: {title:
  '迪桑特开发中心'}, 6200: {title: '东莞站瑞底厂'}, 1600: {title: '安乡大旺'}, 1700: {title: '阳新龙行天下'}, 2300: {title: '越南富存'}, 2400: {title:
  '越南大可'}, 1500: {title: '龙行天下（二厂）'}, 1301: {title: '湖南NB厂'}, 8100: {title: '站佳事业部'}, 9000: {title: '东莞站成研创'}, 1100: {title:
  '东莞站成一厂'}, 1200: {title: '东莞站成二厂'}, 1300: {title: '湖南一厂'}, 1400: {title: '钟祥鞋厂'}, 2100: {title: '越南一厂'}, 2200: {title:
  '越南二厂'}, 6100: {title: '湖南站成底厂'}, 5100: {title: '东莞喜悦鞋材'}, 6400: {title: '钟祥底厂'}, 2600: {title: '龙行天耀'}, 7100: {title:
  '原力3D'}, 7200: {title: '杰富亿'}, 1501: {title: '常德站成'} }[d.orgId]; }}
  <span>{{ orgId.title }}</span>
</script> -->

<!-- <script type="text/html" id="approvals-billstdNo">
    {{#
    let billstdNo = {
    DESTORY: {title: '量产销毁'},
    DESTORY_Y: {title: '样品销毁'}
    }[d.billstdNo];
    }}
    <span>{{ billstdNo.title }}</span>
</script> -->
<script type="text/html" id="approvals-option">
  <span shiro:lacksPermission="approvals:view,approvals:update,approvals:sign"> <span class="layui-badge-dot febs-bg-orange"></span> 无权限 </span>
  <a lay-event="detail" shiro:hasPermission="approvals:view"><i class="layui-icon febs-edit-area febs-green"></i>详情</a>
  <!--  <a lay-event="viewDetail" shiro:hasPermission="approvals:view"><i class="layui-icon febs-edit-area febs-green"></i>明细</a>-->
  <a lay-event="sign" shiro:hasPermission="approvals:sign"> <i class="layui-icon febs-edit-area febs-red"></i>签核</a>
  <a lay-event="flow" shiro:hasPermission="approvals:view"><i class="layui-icon febs-edit-area febs-blue"></i>流程</a>
</script>
<script data-th-inline="none" type="text/javascript">
  layui.use(["dropdown", "jquery", "laydate", "form", "table", "febs", "api"], function () {
    let $ = layui.jquery,
            laydate = layui.laydate,
            febs = layui.febs,
            form = layui.form,
            table = layui.table,
            dropdown = layui.dropdown,
            api = layui.api,
            $view = $("#febs-approvals"),
            $query = $view.find("#query"),
            $reset = $view.find("#reset"),
            $searchForm = $view.find("form"),
            $batchSign = $view.find("#batchSign"),
            sortObject = { field: "sendDate", type: null },
            tableIns,
            createTimeFrom,
            createTimeTo;
    //渲染类型下拉菜单
    febs.get(ctx + "baseflow/getList", null, function (datas) {
      const basestdNoes = datas.data;
      $.each(basestdNoes, function (index, item) {
        $("#billstdNo").append(new Option(item.billstdNo + "-" + item.billstdNm, item.billstdNo)); // 下拉菜单里添加元素
        //重新渲染
        layui.form.render("select");
      });
    });
    //渲染机构下拉菜单
    febs.get(ctx + "classify/getOrgList", null, function (datas) {
      const basestdNoes = datas.data;
      // console.log('basestdNoes',basestdNoes)
      $.each(basestdNoes, function (index, item) {
        $("#orgId").append(new Option(item.orgId + "-" + item.shortnmT, item.orgId)); // 下拉菜单里添加元素
        //重新渲染
        layui.form.render("select");
      });
    });

    form.render();

    initTable();

    laydate.render({
      elem: "#user-signTime",
      range: true,
      trigger: "click",
    });

    dropdown.render({
      elem: $view.find(".action-more"),
      click: function (name, elem, event) {
        let checkStatus = table.checkStatus("approvalTable");
        sessionStorage.setItem("parameterReject", JSON.stringify(checkStatus.data));
        let orderNos = [];
        layui.each(checkStatus.data, function (key, item) {
          orderNos.push(item.orderNo);
        });
        let orderNoData = orderNos.join(",");
        if (name === "reject") {
          if (!checkStatus.data.length || checkStatus.data.length > 1) {
            febs.alert.warn("请选择需要驳回的单据且仅限一条");
          } else {
            febs.modal.open("驳回单据", "approval/approvals/reject", {
              area: $(window).width() <= 750 ? "95%" : "50%",
              offset: ($(window).height() - 506) / 2,
            });
          }
        }
        if (name === "batchSign") {
          if (!checkStatus.data.length) {
            febs.alert.warn("请选择需要签核的单据");
          } else {
           // console.log('checkStatus',checkStatus)
            febs.modal.confirm("签核单据", "确定批量签核已选单据？", function () {
              signApprovalsBatch(checkStatus.data);
            });
          }
        }
      },
      options: [
        {
          name: "reject",
          title: "单个驳回",
          perms: "reject:view",
        },
         {
            name: "batchSign",
            title: "批量签核",
            perms: "approvals:sign",
          }
      ],
    });

    /* 监听行事件*/
    table.on("tool(approvalTable)", function (obj) {
      let data = obj.data,
              layEvent = obj.event;
      console.log(obj.data); //得到当前行数据
      sessionStorage.setItem("parameterData", JSON.stringify(obj.data));
      if (layEvent === "detail") {
        //详情
        let str = window.location.href;
        let num = str.indexOf("index#"); //返回NUM
        let openUrl = str.substring(0, num) + "febs/views/approval/approvals/approvalsDetail";
        console.log("openUrl", openUrl);
        window.open(openUrl);
        //reportApprovals(data);
      }
      if (layEvent === "sign") {
        // febs.modal.confirm("签核流程", "确定签核单据编号【 " + data.orderNo + "】？", function () {
        //   signApprovals(data);
        // });
        // console.log("log", data);
        febs.modal.view("单据签核", "/approval/approvals/approvalsSign", {
          area: $(window).width() <= 750 ? "100%" : "100%",
          offset:0
          // offset: ($(window).height() - 600) / 2,
        });
        // let str = window.location.href;
        // let num = str.indexOf("index#"); //返回NUM
        // let openUrl = str.substring(0, num) + "febs/views/approval/approvals/approvalsSign";
        // window.open(openUrl);
      }
      if (layEvent === "edit") {
        febs.modal.open("修改流程", "approval/approvals/update/" + data.basestdNo, {
          area: $(window).width() <= 750 ? "90%" : "50%",
          btn: ["提交", "取消"],
          yes: function (index, layero) {
            $("#user-update").find("#submit").trigger("click");
          },
          btn2: function () {
            layer.closeAll();
          },
        });
      }
      if (layEvent === "flow") {
        febs.modal.view("流程信息", "/approval/approvals/signDetails", {
          area: $(window).width() <= 750 ? "95%" : "760px",
          offset: "auto",
          offset: "180px",
        });
      }
      if (layEvent === "viewDetail") {
        febs.modal.view("明细", "/approval/approvals/approvalsDetailTable", {
          area: $(window).width() <= 1600 ? "100%" : "1600px",
          offset: "auto",
          offset: "100px",
        });
      }
    });

    table.on("sort(approvalTable)", function (obj) {
      sortObject = obj;
      tableIns.reload({
        initSort: obj,
        where: $.extend(getQueryParams(), {
          field: obj.field,
          order: obj.type,
        }),
      });
    });

    $query.on("click", function () {
      console.log(sortObject);
      let params = $.extend(getQueryParams(), { field: sortObject.field, order: sortObject.type });
      tableIns.reload({ where: params, page: { curr: 1 } });
    });
    $reset.on("click", function () {
      $searchForm[0].reset();
      sortObject.type = "null";
      createTimeTo = null;
      createTimeFrom = null;
      tableIns.reload({ where: getQueryParams(true), page: { curr: 1 }, initSort: sortObject });
    });
    $batchSign.on("click", function () {
      let checkStatus = table.checkStatus("approvalTable");
      if (!checkStatus.data.length) {
        febs.alert.warn("请选择需要签核的单据");
      } else {
        // console.log('checkStatus',checkStatus)
        febs.modal.confirm("签核单据", "确定批量签核已选单据？", function () {
          signApprovalsBatch(checkStatus.data);
        });
      }
    });

    function initTable() {
      tableIns = febs.table.init({
        elem: $view.find("table"),
        id: "approvalTable",
        url: ctx + "approvals/list",
        // parseData: (res) => {
        //   console.log(res);
        //   res.data.rows.forEach((res) => {
        //     res.billstdNm = api.nameFormate(res.billstdNo);
        //     res.orgNm = api.getOrgNm(res.orgId);
        //   });
        parseData: function (res) {
          console.log(res);
          res.data.rows.forEach(function (res) {
            res.billstdNm = api.nameFormate(res.billstdNo);
            res.orgNm = api.getOrgNm(res.orgId);
          });
          return {
            code: 0, //解析接口状态
            data: res.data.rows, //解析数据列表
            count: res.data.total, //解析数据长度
          };
        },
        cols: [
          [
            { type: "checkbox" },
            { field: "orgNm", title: "组织机构", minWidth: 120},
            { field: "billstdNm", title: "单据类别" },
            { field: "orderNo", title: "单据编号",minWidth: 80},
            { field: "grtUserCname", title: "送签人员", minWidth: 15 },
            { field: "grtUser", title: "送签人员", disabled: true, hide: true },
            { field: "sendDate", title: "送签日期", minWidth: 110 },
            { field: "toUserCname", title: "签核人员" },
            { field: "toUser", title: "签核人员", disabled: true, hide: true },
            { field: "flowDesc", title: "签核角色", minWidth: 10 },
            { field: "chkDate", title: "签核时间", disabled: true, hide: true },
            { field: "nextUser", title: "下个签核人员", hide: true },
            { field: "nextFlow", title: "下个流程序号", hide: true },
            { field: "isLast", title: "最好一个签核", hide: true },
            { field: "orgId", title: "组织id", hide: true },
            { field: "chkStatus", title: "签核状态", hide: true },
            { field: "chkmgrId", title: "签核id", hide: true },
            { field: "planEtime", title: " 时间转换禁用", hide: true },
            { field: "factEtime", title: "时间转换禁用", hide: true },
            { field: "readDaate", title: "时间转换禁用", hide: true },
            { field: "noteId", title: "当前节点", hide: true },
            { title: "状态", templet: "#approvals-status" },
            { title: "操作", toolbar: "#approvals-option", minWidth: 150 },
          ],
        ],
      });
    }

    function getQueryParams(flag) {
      let params = $searchForm.serializeJson();
      let sendDate = params.time;
      if (sendDate) {
        createTimeFrom = sendDate.split(" - ")[0];
        createTimeTo = sendDate.split(" - ")[1];
      }
      params.invalidate_ie_cache = new Date();
      params.createTimeFrom = createTimeFrom;
      params.createTimeTo = createTimeTo;
      return params;
    }

    function signApprovals(data) {
      $.ajax({
        type: "post",
        url: ctx + "approvals/sign",
        dataType: "json",
        data: JSON.stringify(data),
        contentType: "application/json;charset=UTF-8",
        success: function () {
          febs.alert.success(data.orderNo + " 签核单据成功");
          $query.click();
        },
      });
    }
    function signApprovalsBatch(data) {
      $.ajax({
        type: "post",
        url: ctx + "approvals/batchSign",
        dataType: "json",
        data: JSON.stringify(data),
        contentType: "application/json;charset=UTF-8",
        success: function () {
          let orderNos = [];
          layui.each(data, function (key, item) {
            orderNos.push(item.orderNo);
          });
          let orderNoData = orderNos.join(",");
          febs.alert.success("【 " + orderNoData + "】签核单据成功");
          $query.click();
        },
      });
    }
    function reportApprovals(data) {
      $.ajax({
        type: "post",
        url: ctx + "approvals/report",
        dataType: "json",
        data: JSON.stringify(data),
        contentType: "application/json;charset=UTF-8",
        success: function () {
          // febs.alert.success(data.orderNo + ' 签核单据成功');
          //$query.click();
          febs.modal.view("详情信息", {
            area: $(window).width() <= 750 ? "95%" : "660px",
          });
        },
      });
    }
  });
</script>
